package com.jh3502.helper.function.login;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.method.KeyListener;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.jh3502.helper.BuildConfig;
import com.jh3502.helper.R;
import com.jh3502.helper.base.BaseActivity;
import com.jh3502.helper.function.home.HomeActivity;
import com.jh3502.helper.utils.SpHelper;
import com.jh3502.helper.utils.Utils;
import com.jh3502.helper.view.CircularAnim;
import com.jh3502.helper.view.SnackbarUtil;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnTextChanged;
import cxy.com.validate.SimpleValidateResult;
import cxy.com.validate.Validate;
import cxy.com.validate.annotation.Index;
import cxy.com.validate.annotation.NotNull;

/**
 * @author harisucici
 */
public class LoginActivity extends BaseActivity implements LoginPresenter.LoginView {

    @Nullable
    @Index(0)
    @NotNull(msg = "请输入姓名！")
    @BindView(R.id.login_phone)
    EditText loginPhone;

    @Nullable
    @Index(1)
    @NotNull(msg = "请输入密码!")
    @BindView(R.id.login_pass)
    EditText loginPass;

    @Nullable
    @BindView(R.id.login_delete)
    ImageView loginDelete;

    @Nullable
    @BindView(R.id.login_progress)
    ProgressBar loginProgress;
    @Nullable
    @BindView(R.id.login_submit)
    Button loginSumit;
    @BindView(R.id.login_version)
    TextView loginVersion;
    private LoginPresenter loginPresenter;

    private KeyListener keyListener;

    @Override
    protected int setViewId() {
        return R.layout.activity_login;
    }

    @Override
    protected void initView() {
        requestPermission();
        loginVersion.setText(getResources().getString(R.string.app_name) + BuildConfig.VERSION_NAME);
        loginPresenter = new LoginPresenter();
        loginPresenter.setLoginView(this);
        keyListener = loginPass.getKeyListener();

        loginPass.setText("wanghuiling");

        loginPhone.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                boolean isOK = false;
                if (actionId == EditorInfo.IME_ACTION_NEXT || (event != null
                        && KeyEvent.KEYCODE_ENTER == event.getKeyCode()
                        && KeyEvent.ACTION_DOWN == event.getAction())) {
                    loginPass.requestFocus();
                    isOK = true;
                }
                return isOK;
            }
        });
        loginPass.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                boolean isOK = false;
                if (actionId == EditorInfo.IME_ACTION_SEND || (event != null
                        && KeyEvent.KEYCODE_ENTER == event.getKeyCode()
                        && KeyEvent.ACTION_DOWN == event.getAction())) {
                    if (isWifiConnect()) {
                        Map<String, Object> body = new HashMap<>(2);
                        body.put("username", loginPhone.getText().toString().trim());
                        body.put("password", loginPass.getText().toString().trim());
                        CircularAnim.hide(loginSumit).endRadius(loginProgress.getHeight() / 2)
                                .go(() -> {
                                    loginPhone.setKeyListener(null);
                                    loginPass.setKeyListener(null);
                                    loginProgress.setVisibility(View.VISIBLE);
                                    loginPresenter.toLogin(body);
                                });
                    } else {
                        if (loginPass.getText().toString().trim().equals(SpHelper.getInstance().getPassword())
                                && loginPhone.getText().toString().trim().equals(SpHelper.getInstance().getUserName())) {
                            Utils.getInstance().startActivity(LoginActivity.this, HomeActivity.class, true);
                        } else {
                            showShortToast("密码不正确", SnackbarUtil.ALERT);
                        }
                    }
                    isOK = true;
                }
                return isOK;
            }
        });

    }

    @Override
    protected void initData() {
//        String token = SpHelper.getInstance().getToken();
//        if (token.length() > 0) {
//            Utils.getInstance().startActivity(LoginActivity.this, HomeActivity.class, true);
//        }
        String userName = SpHelper.getInstance().getUserName();
        loginPhone.setText(userName);

    }

    @Override
    protected void doOnDestroy() {

    }

    @Override
    protected void doOnResume() {

    }

    @Override
    protected void doOnSaveInstanceState(Bundle savedInstanceState) {

    }


    @OnClick(R.id.login_submit)
    public void onLoginSubmitClicked() {
        if (Utils.getInstance().isFastDoubleClick()) {
            return;
        }
        Validate.check(this, new SimpleValidateResult() {
            @Override
            public void onValidateSuccess() {
                if (isWifiConnect()) {
                    Map<String, Object> body = new HashMap<>(2);
                    body.put("username", loginPhone.getText().toString().trim());
                    body.put("password", loginPass.getText().toString().trim());
                    CircularAnim.hide(loginSumit).endRadius(loginProgress.getHeight() / 2)
                            .go(() -> {
                                loginPhone.setKeyListener(null);
                                loginPass.setKeyListener(null);
                                loginProgress.setVisibility(View.VISIBLE);
                                loginPresenter.toLogin(body);
                            });
                } else {
                    if (loginPass.getText().toString().trim().equals(SpHelper.getInstance().getPassword())
                            && loginPhone.getText().toString().trim().equals(SpHelper.getInstance().getUserName())) {
                        Utils.getInstance().startActivity(LoginActivity.this, HomeActivity.class, true);
                    } else {
                        showShortToast("密码不正确", SnackbarUtil.ALERT);
                    }
                }
            }

            @Override
            public void onValidateError(@NonNull String msg, EditText editText) {
                showShortToast(msg, SnackbarUtil.ALERT);
            }
        });
    }


    @Override
    public void loginSuccess(@NonNull Map<String, Object> map) {
        SpHelper.getInstance().saveAll(map);
        SpHelper.getInstance().setUserName(loginPhone.getText().toString());
        SpHelper.getInstance().setPassword(loginPass.getText().toString());
        Utils.getInstance().startActivity(LoginActivity.this, HomeActivity.class, true);
    }

    @OnClick(R.id.login_delete)
    public void onLoginDeleteClicked() {
        loginPhone.setText("");
        loginPass.setText("");
    }

    @OnTextChanged(value = R.id.login_phone, callback = OnTextChanged.Callback.TEXT_CHANGED)
    void onTextChangedPhone(CharSequence s, int start, int before, int count) {
        if (loginPhone.getText().toString().trim().length() > 0) {
            loginDelete.setVisibility(View.VISIBLE);
        } else {
            loginDelete.setVisibility(View.GONE);
        }

    }

    @Override
    public void responseError(int code, String msg) {
        showShortToast(msg);
        loginProgress.setVisibility(View.GONE);
        CircularAnim.show(loginSumit).go();
        loginPhone.setKeyListener(keyListener);
        loginPass.setKeyListener(keyListener);
    }

    private boolean isWifiConnect() {
//        ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
//        NetworkInfo mWifiInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
//        return mWifiInfo.isConnected();
        ConnectivityManager manager =
                (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);

        if (manager == null) {
            return false;
        }
        NetworkInfo networkinfo = manager.getActiveNetworkInfo();
        if (networkinfo == null || !networkinfo.isAvailable()) {
            return false;
        }
        return true;
    }

}
